#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import abort, jsonify
from flask import current_app, g, render_template, request
from flask import session

from info import constants, db
from info.models import News, Comment, CommentLike, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu


@news_blu.route("/followed_user",methods=["post"])
@user_login_data
def followed_user():
    """关注和取消关注"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 获取新闻作者的id 和行为
    user_id = request.json.get("user_id")
    action = request.json.get("action")
    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
    if action not in ["follow","unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户信息")
    # 根据不同的操作做不同的逻辑
    if action =="follow":
        if target_user not in user.followed:
            user.followed.append(target_user)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="已关注过该用户")
    else:
        if target_user in user.followed:
            user.followed.remove(target_user)
        else:
            return jsonify(errno=RET.NODATA, errmsg="该用户未被关注")
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route("/comment_like", methods=["post"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    req = request.json
    comment_id = req.get("comment_id")
    action = req.get("action")
    news_id = req.get("news_id")

    if not all([comment_id, action]):
        print(comment_id)
        # print(news_id)
        print(action)
        return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="缺少操作参数")

    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    if action == "add":
        try:
            comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                          CommentLike.user_id == user.id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        if not comment_like_model:
            comm_like = CommentLike()
            comm_like.comment_id = comment_id
            comm_like.user_id = user.id
            try:
                db.session.add(comm_like)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()

            comment.like_count += 1
    else:
        try:
            comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                          CommentLike.user_id == user.id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        if comment_like_model:

            try:
                db.session.delete(comment_like_model)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
            comment.like_count -= 1

    return jsonify(errno=RET.OK, errmsg="OK")


@news_blu.route("/news_comment", methods=["post"])
@user_login_data
def comment_news():
    """
    1.获取参数 用户g，新闻id：，评论的参数 （id，内容） 父评论的id（通过这个来判断）
    2.用户是否登录，没登录弹窗登录，登录后才能评论
    3.检查参数（是否都有值，参数类型是否正确，评论的新闻是否存在）
    4.提交评论时候将评论数据保存到数据库评论表里

    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    req = request.json
    news_id = req.get("news_id")
    comment_content = req.get("comment")
    parent_id = req.get("parent_id")

    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数缺失")

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数类型错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="查询的新闻不存在")

    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        print("parent_id:", parent_id)
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    data = {
        "comment": comment.to_dict()
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@news_blu.route("/news_collect", methods=["post"])
@user_login_data
def news_collect():
    """
    1.获取参数 和 通过g获取用户   news_id , active
    2.校验参数 用户是否存在，参数类型是否正确
    3.校验用户，未登录的话提示登录
        查询新闻是否存在，不存在就return
    4.通过active判断用户操作，查询用户是否有收藏该新闻
    5.通过active的值判断是收藏还是取消收藏
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    req = request.json
    news_id = req.get("news_id", "")
    action = req.get("action", "")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数缺少")

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="收藏参数错误")

    # 校验参数news_id类型
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="新闻参数错误")

    # 查询新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.NODATA, errmsg="数据查询错误")
    # 判断操作类型
    if action == "collect":
        # 判断是否有收藏，没收藏就添加收藏
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    """
    通过news_id来查询数据
    将查询到的数据封装到data中返回给前端显示，并且将数据点击量+1
    :param news_id:
    :return:
    """

    # 获取点击排行的数据
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    rank_news_list = []
    for l_news in news_list if news_list else []:
        rank_news_list.append(l_news.to_basic_dict())

    # 通过g变量过去到user模型对象
    user = g.user
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        abort(404)
    news.clicks += 1
    # 当前登录用户是否关注当前新闻作者
    is_followed = False

    # 判断是否收藏该新闻，默认值为 false
    is_collected = False
    # 判断用户是否收藏过该新闻
    if user:
        if news in user.collection_news:
            is_collected = True
        if news.user in user.followed:
            is_followed = True

    # 获取当前新闻的评论
    # 评论点赞
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_list = []
    for item in comments:
        comment_dict = item.to_dict()
        comment_dict["is_like"] = False
        if user:
            comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                     CommentLike.comment_id == item.id).first()
            if comment_likes:
                comment_dict["is_like"] = True
        comment_list.append(comment_dict)

    data = {
        "user_info": user.to_dict() if user else None,
        "news": news.to_dict(),
        "rank_news_list": rank_news_list,
        "is_collected": is_collected,
        "comments": comment_list,
        "is_followed":is_followed
    }
    return render_template("news/detail.html", data=data)
